package cn.haoo.controller;

import cn.haoo.pojo.*;
import cn.haoo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/item")
public class ItemEidtController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private UserService userService;
    @Autowired
    private GreatService greatService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private HandselServer handselServer;

    /*发帖页面*/
    @GetMapping("/add")
    public String addItem(Model model, HttpSession session) {
        System.out.println("getmapping /add");
        int iid = itemService.selectAll().get(0).getIid() + 1;
        session.setAttribute("iid", iid);
        return "/item/add";
    }

    @PostMapping("/add")
    public String postItem(Model model, Item item, String htime, String vercode) {
        System.out.println("postmapping /add");
        System.out.println(htime);
        System.out.println("添加的item是：" + item.toString());
        itemService.insertSelective(item);
        item = itemService.selectAll().get(0);
        System.out.println("经过mysql的item是：" + item.toString());
        if (htime != null && htime != "") {
            Handsel handsel = new Handsel();
            handsel.setIid(item.getIid());
            handsel.setHtime(strToDateLong(htime));
            handselServer.insertSelective(handsel);
        }
        return "redirect:/item/detail?iid=" + item.getIid();
    }

    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("/add/upimg")
    public String itemUpimg(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        Integer iid = (Integer) session.getAttribute("iid");
        //上传路径保存设置
        System.out.println("开始上传图片");
        String path = request.getServletContext().getRealPath("/static/images/item");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);

        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath + "/" + iid + ".png"));
        return "/item/add";
    }

    @GetMapping("/getimg")
    @ResponseBody
    public String getPic(HttpServletResponse response, HttpServletRequest request, int iid) throws Exception {
        String path = request.getServletContext().getRealPath("/static/images/item");
        String fileName = iid + ".png";
        String defaultfileName = "default.png";

        //1、设置response 响应头
        //response.reset(); //设置页面不缓存,清空buffer
        //response.setCharacterEncoding("UTF-8"); //字符编码
        //response.setContentType("multipart/form-data"); //二进制传输数据
        response.setContentType("image/png");
        /*
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
        */
        File file = new File(path, fileName);
        if (!file.exists()) {   //如果文件不存在
            file = new File(path, defaultfileName);
        }
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

    @GetMapping("/update")
    public String addSelectItem(Model model, HttpSession session, int iid) {
        model.addAttribute("item", itemService.selectByPrimaryKey(iid));
        model.addAttribute("htime", handselServer.selectByIid(iid));
        session.setAttribute("iid", iid);
        return "/item/add";
    }

    @PostMapping("/update")
    public String updateItem(Model model, Item item, String htime, String vercode) {
        System.out.println("postmapping /add");
        System.out.println(htime);
        if (htime != null && htime != "") {
            Handsel handsel = new Handsel();
            handsel.setIid(item.getIid());
            handsel.setHtime(strToDateLong(htime));
            if (handselServer.selectByIid(handsel.getIid()) != null)
                handselServer.updateByPrimaryKeySelective(handsel);
            else handselServer.insertSelective(handsel);
        }
        System.out.println("更新的item是：" + item.toString());
        itemService.updateByPrimaryKeySelective(item);
        item = itemService.selectAll().get(0);
        System.out.println("经过mysql的item是：" + item.toString());

        return "redirect:/item/detail?iid=" + item.getIid();
    }

    @RequestMapping("/delete")
    public String deleteItem(Model model, HttpSession session, int iid) {
        Item item = itemService.selectByPrimaryKey(iid);
        User user = (User) session.getAttribute("user");
        if (!item.getUid().equals(user.getUid())) {
            return "redirect:/item/detail?iid=" + item.getIid();
        }
        System.out.println("删除了" + item.toString());
        itemService.deleteByPrimaryKey(item.getIid());
        return "redirect:/index";

    }

    @RequestMapping("/over")
    public String overItem(Model model,int iid){
        Item item =itemService.selectByPrimaryKey(iid);
        if(item.getItype()==3)
            item.setItype(4);
        return "redirect:/item/detail?iid=" + item.getIid();
    }

    /*帖详情*/
    @RequestMapping("/detail")
    public String detailItem(Model model, int iid) {
        Item itemdetail = new Item();
        List<Comment> commentList = new ArrayList<Comment>();

        itemdetail = itemService.selectByPrimaryKey(iid);
        commentList = commentService.selectAllByIid(iid);
        itemdetail = viewUp(itemdetail);

        model.addAttribute("item", itemdetail);
        model.addAttribute("itemview", ShowItemView(itemdetail));
        model.addAttribute("clist", ShowCommentView(commentList));
        return "/item/detail";
    }

    @RequestMapping("/great")
    public String giveGreat(Model model, HttpSession session, int iid, int cid) {
        User user = (User) session.getAttribute("user");
        Great great = new Great();

        great.setIid(iid);
        great.setUid(user.getUid());
        if (cid != -1)
            great.setCid(cid);

        System.out.println(great.toString());
        greatService.insertSelective(great);
        return "redirect:/item/detail?iid=" + iid;
    }

    public List<CommentView> ShowCommentView(List<Comment> list) {
        List<CommentView> listview = new ArrayList<CommentView>();
        for (int i = 0; i < list.size(); i++) {
            //开始循环
            Comment comment = list.get(i);
            //list中添加
            listview.add(SerchCom(comment));
        }
        return listview;
    }

    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    public CommentView SerchCom(Comment comment) {
        User user = userService.selectByPrimaryKey(comment.getUid());
        CommentView view = new CommentView();
        int great = greatService.selectByCid(comment.getCid());
        view.setComment(comment);
        view.setUser(user);
        view.setGreat(great);
        if (comment.getCidp() != null) {
            System.out.println("被评论的是cid" + comment.getCidp());
            Comment commentp = commentService.selectByPrimaryKey(comment.getCidp());
            System.out.println("被评论的是他" + commentp.toString());
            User userp = userService.selectByPrimaryKey(commentp.getUid());
            view.setCommentp(commentp);
            view.setUserp(userp);
        }
        return view;
    }

    /*从数据库中拿出detail需要列出的item信息*/
    public IndexView ShowItemView(Item item) {
        IndexView itemview = new IndexView();
        itemview.setIndexView(item, userService.selectByPrimaryKey(item.getUid()),
                greatService.selectByIid(item.getIid()), commentService.selectByIid(item.getIid()));
        return itemview;
    }

    public Item viewUp(Item item) {
        System.out.println("奇怪的浏览量增加了");
        item.setIbrowse(item.getIbrowse() + 1);
        itemService.updateByPrimaryKeySelective(item);
        return itemService.selectByPrimaryKey(item.getIid());
    }
}
